import {createCustomComponent,createExtPage} from '@/utils/util'

// 前端未找到页面路由（固定不用改）
const notFoundRouter = {
  path: '*', redirect: '/404', hidden: true
}


const rootRouter = [

  {
    path: '/',
    name: 'index',
    component: 'BasicLayout',
    meta: { title: 'home',layouts:'layouts',keyId:'k001' },
    redirect: '/dashboard/workplace',
    children: [
      {
        path: '/dashboard/workplace',
        name: 'Workplace',
        component: 'dashboard/Workplace',
        meta: { title: '主页',keyId:'k002'}
      },
      
    ]
  }
]




/**
 * 动态生成菜单
 * @param 登陆人信息
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = (userInfo) => {
  return new Promise((resolve, reject) => {
      const { menus } = userInfo
      //将后台得到的路由和根路由拼接
      menus.forEach(item => {
        rootRouter[0].children.push(item);
      })
      const routers = generator(rootRouter)

      //404一定要放到最后
      routers.push(notFoundRouter)
    //   console.log(routers)
      resolve(routers)
  })
}

/**
 * 格式化树形结构数据 生成 vue-router 层级路由表
 *
 * @param routerMap
 * @param parent
 * @returns {*}
 */
export const generator = (routerMap, parent) => {

  return routerMap.map(item => {
    const { title ,icon,pageId,extLink,isNewWin} = item.meta || {}
    const currentRouter = {
        
      // path 一定要唯一
      path: pageId?item.path+'/'+pageId:item.path,
      // 路由名称，唯一
      name: item.name,

      meta: {
        title: title,
        icon: icon || undefined,
        pageId:pageId || undefined,
        extLink:extLink || undefined,
        isNewWin:isNewWin || undefined
      }
    }
    if(extLink){
        currentRouter.component  = createExtPage('page'+item.keyId,extLink)
    }else if( (item.meta && item.meta.layouts) || item.component=="RouteView"){
        currentRouter.component  = (() => import(`@/layouts/${item.component}`))
    }else if(pageId){
        currentRouter.component  = createCustomComponent('page'+pageId, import(`@/views/${item.component}`))
    }else{
        currentRouter.component  = (() => import(`@/views/${item.component}`))
    }
   
    // 为了防止出现后端返回结果不规范，处理有可能出现拼接出两个 反斜杠
    if (!currentRouter.path.startsWith('http')) {
      currentRouter.path = currentRouter.path.replace('//', '/')
    }
    // 重定向
    item.redirect && (currentRouter.redirect = item.redirect)
    // 是否有子菜单，并递归处理
    if (item.children && item.children.length > 0) {
      // Recursion
      
      currentRouter.children = generator(item.children, currentRouter)
    }
    return currentRouter
  })
}
